var app = getApp()
Component({
  options: {
    styleIsolation: 'shared' 
  },
  properties: {
    scrollViewWidth: {
      type: null,
      value: 0,
    },
    allDataList: {
      type: null,
      value: {},
    },
    activeIndex: {
      type: null,
      value: 0,
    }
  },
  /**
   * 页面的初始数据
   */
  data: {
    searchVal: "",
    scrollLeft: 0,
    lineOffsetLeft: 0,
    scrollTop: 0,
    active: "",
    selectLevelGoods: [], //选中等级商品
    saveGoodsData: [],
    goodsData: [],
    tab_index: 0
  },

  lifetimes: {
    attached() {
      this.getLevelData();
    }
  },
  methods: {
    // 取消
    cancal() {
      this.triggerEvent('cancalEvent', false)
    },
    // 搜索款数据
    onChangeSearch(e) {
      this.setData({
        searchVal: e.detail,
      });
    },
    // 选择复选框
    onChange(e) {
      let index = e.currentTarget.dataset.index;
      let ifMealData = "goodsData[" + index + "].checked";
      this.setData({
        [ifMealData] : !this.data.goodsData[index].checked,
      })
      this.setData({
        selectLevelGoods : this.filterData()
      })
    },
    // 选择等级
    chooseLevel(e) {
      if(e.currentTarget.offsetLeft || e.currentTarget.offsetLeft == 0) {
        this.setData({
          active: e.currentTarget.dataset.value.id,
        })

        let offsetLeft = e.currentTarget.offsetLeft 
        this.setData({
            scrollLeft: (offsetLeft - this.data.scrollViewWidth / 2) + 33,
            scrollTop: 0,
            tab_index: e.currentTarget.dataset.index
        })
        this.setLine(e.currentTarget.dataset.index);
      }

      let newData = this.data.goodsData.filter(item => item.checked)
      let newArr = [...newData, ...this.data.saveGoodsData]
      this.setData({
        saveGoodsData: newArr
      })

      this.searchActivityGoods();
    },
    setLine(currentIndex) {
      Promise.all([
        this.getAllRect.call(this, '.tabs-rol'),
        this.getRect.call(this, '.active-line'),
      ]).then(([rects = [], lineRect]) => {
        const rect = rects[currentIndex];
        if (rect == null) {
          return;
        }
        let lineOffsetLeft = rects
          .slice(0, currentIndex)
          .reduce((prev, curr) => prev + curr.width, 0);
        lineOffsetLeft += (rect.width - lineRect.width) / 2;
        this.setData({
          lineOffsetLeft: lineOffsetLeft - 30,
        });
      });
    },
     getAllRect(selector) {
      return new Promise((resolve) => {
        wx.createSelectorQuery()
          .in(this)
          .selectAll(selector)
          .boundingClientRect()
          .exec((rect = []) => resolve(rect[0]));
      });
    },
    getRect(selector) {
      return new Promise((resolve) => {
        wx.createSelectorQuery()
          .in(this)
          .select(selector)
          .boundingClientRect()
          .exec((rect = []) => resolve(rect[0]));
      });
    },
    touchBottom(){ 
      // console.log(112335);
    },
   // 获取等级数据
   getLevelData() {
      app._postNetWork({
        url: app.getNetAddresss('plugin.new-blind-box.frontend.activity.activity-level'),
        data: {id: this.data.allDataList.list[this.data.activeIndex].id},
        success: ({data}) => {
          if(data.result) {
            let selectLevelGoods = []
            for(let item of data.data.list) {
              selectLevelGoods.push({
                level_id: item.id,
                goods: [],
                level_name: item.level_name,
                id: item.id,
                pivot: item.pivot
              })
            }
            this.setData({
              active: data.data.list[0].id,
              selectLevelGoods
            })
            this.searchActivityGoods();
          }else {
            wx.showToast({
              icon: 'none',
              title: data.msg,
              duration: 1500
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      })
    },
    searchActivityGoods() {
      app._postNetWork({
        url: app.getNetAddresss('plugin.new-blind-box.frontend.activity.search-activity-goods'),
        data: {
          id: this.data.allDataList.list[this.data.activeIndex].id , 
          level_id : this.data.active, 
          search : {
            goods_keyword : this.data.searchVal
          }
        },
        success: ({data}) => {
          if(data.result) {
            this.setData({
              goodsData: data.data.goods
            })
            for(let item of this.data.goodsData) {
              item.level_id  = this.data.active;
              for(let citem of this.data.saveGoodsData){
                if(item.goods_id == citem.goods_id) {
                  let index = this.data.goodsData.findIndex(vitem => vitem.goods_id == citem.goods_id);
                  let cindex = this.data.saveGoodsData.findIndex(vitem => vitem.goods_id == citem.goods_id);
                  if(index !== -1) {
                    this.data.saveGoodsData.splice(cindex,1)
                  }
                  if(index !== -1) {
                    this.setData({
                      ["goodsData[" + index + "].checked"] : true
                    })
                  }
                }
              }
            }

            this.setData({
              selectLevelGoods: this.filterData()
            })
          }else {
            wx.showToast({
              icon: 'none',
              title: data.msg,
              duration: 1500
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      })
    },
    filterData() {
      let checkedGoodsData = this.data.goodsData.filter(item => item.checked);
      let checkedData = [...checkedGoodsData,...this.data.saveGoodsData];
      let select_goods = JSON.parse(JSON.stringify(this.data.selectLevelGoods));
      for(let item of select_goods) {
        item.goods = []
      }
      for(let item of checkedData) {
        for(let citem of select_goods) {
          if(item.level_id == citem.level_id) {
            citem.goods.push({
              goods_id: item.goods_id,
              goods_option_id: item.goods_option_id
            })
          }
        }
      }
      
      return select_goods
    },
    // 跳转到详情
    goOrderPage() {
      let select_goods = this.filterData().map(item => {
        return {
          goods: item.goods,
          level_id: item.level_id
        }
      });

      wx.navigateTo({
        url: '/packageD/buy/myOrder_v2/myOrder_v2?tag=-2&optionsId=&total=1&goodsId=' + this.data.allDataList.list[this.data.activeIndex].goods_id+`&activity_id=${this.data.allDataList.list[this.data.activeIndex].id}&select_goods=${JSON.stringify(select_goods)}&name=newBlindBox`,
      });
    }
  },

})